package com.quanyan.club.web;

import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.club.constants.ClubConstants;
import com.quanyan.club.entity.db.TbClubMultimedia;
import com.quanyan.club.entity.db.TbSystemParameters;
import com.quanyan.club.entity.db.TbSystemParametersExample;
import com.quanyan.club.entity.vo.resp.task.EggTaskFinishCase;
import com.quanyan.club.entity.vo.resp.task.TaskInfo;
import com.quanyan.club.mapper.TbSystemParametersMapper;
import com.quanyan.club.service.ClubHomePageService;
import com.quanyan.club.service.ClubTaskEggService;
import com.quanyan.common.exception.BizException;
import com.quanyan.redisCluster.config.RedisTemplate;
import com.quanyan.redisCluster.utils.RedisConstants;
import com.quanyan.redisCluster.utils.RedisKey;
import org.apache.commons.collections.MapUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by zhuo.shi on 2016/11/8.
 * 俱乐部主页需要的接口
 * @version 2.1.1
 */
@RestController
@RequestMapping(value = "/api/club/homepage")
public class ClubHomePageController extends BaseController{

    private static Logger logger = Logger.getLogger(ClubHomePageController.class);

    @Autowired
    private ClubHomePageService clubHomePageService;
    @Autowired
    private ClubTaskEggService clubTaskEggService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TbSystemParametersMapper systemParametersMapper;

    @RequestMapping(value = "/index")
    public APIResponse index(@RequestBody Map map, HttpServletRequest request){
        Integer uid = getUid(request, false);
        return APIResponse.returnSuccess(
                clubHomePageService.index(uid, MapUtils.getIntValue(map, "clubId")));
    }

    @RequestMapping(value = "/detail")
    public APIResponse detail(@RequestBody Map map, HttpServletRequest request){
        Integer uid = getUid(request, false);
        return APIResponse.returnSuccess(
                clubHomePageService.detail(uid, MapUtils.getIntValue(map, "clubId")));
    }


    @RequestMapping(value = "/activityList")
    public APIResponse activityList(@RequestBody Map map, HttpServletRequest request){
        Integer uid = getUid(request, false);
        return APIResponse.returnSuccess(
                clubHomePageService.activityList(uid, MapUtils.getIntValue(map, "clubId")));
    }

    @RequestMapping(value = "/getEggTasks")
    public APIResponse<List<EggTaskFinishCase>> award(@RequestBody Map map, HttpServletRequest request){
        if (isDisableTask()){
            List<EggTaskFinishCase> list = new ArrayList<>();
            return APIResponse.returnSuccess(list);
        }
        Integer clubType = MapUtils.getInteger(map, "clubType");
        Integer clubId = MapUtils.getInteger(map, "clubId");
        String ver = MapUtils.getString(map, "ver");
        if (clubType == null || clubId == null){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }

        return APIResponse.returnSuccess(
               clubTaskEggService.getEggTaskFinishCaseList(clubType, clubId, ver));
    }

    private boolean isDisableTask(){
        TbSystemParametersExample example = new TbSystemParametersExample();
        example.createCriteria().andParamKeyEqualTo("week.task.enable");
        List<TbSystemParameters> list = systemParametersMapper.selectByExample(example);
        if (list == null || list.size() == 0){
            return true;
        }
        int v = Integer.valueOf(list.get(0).getParamValue());
        return v>=1;
    }

    @RequestMapping(value = "/giveOutEggs")
    public APIResponse giveOutEggs(@RequestBody Map map, HttpServletRequest request){
        if (isDisableTask()){
            return APIResponse.returnSuccess(new HashMap());
        }

        Integer clubId = MapUtils.getInteger(map, "clubId");
        Long weekDate = MapUtils.getLong(map, "weekDate");
        if (clubId == null || weekDate == null){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        Integer uid = getUid(request, true);
        RedisKey limitKey = new RedisKey(RedisConstants.CLUB_FAMILY_KEY,
                ClubConstants.GIVEOUT_EGG_REDIS_LIMIT + clubId);        //现在一个俱乐部在同一时刻，只能进行一次领鸟蛋操作
        if (redisTemplate.exists(limitKey)){
            throw new BizException("领取鸟蛋中...");
        }else {
            redisTemplate.set(limitKey, clubId);
        }
        Map<String, Object> result = null;
        try {
            result = clubTaskEggService.giveOutEggs(uid, clubId, new Date(weekDate));
        }catch (Exception e){
            redisTemplate.delteKey(limitKey);
            logger.warn("异常" + e.getMessage());
            throw new BizException(e.getMessage());
        }
        redisTemplate.delteKey(limitKey);
        return APIResponse.returnSuccess(result);
    }

    /**
     * 任务中心
     */
    @RequestMapping(value = "/taskCenter")
    public APIResponse awardCenter(@RequestBody Map map){
        if (isDisableTask()){
            List<TaskInfo> list = new ArrayList<>();
            return APIResponse.returnSuccess(list);
        }
        Integer pageNo = MapUtils.getInteger(map, "pageNo");
        Integer pageSize = MapUtils.getInteger(map, "pageSize");
        Integer clubId = MapUtils.getInteger(map, "clubId");
        if (clubId == null || pageNo == null || pageSize == null){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        return APIResponse.returnSuccess(clubTaskEggService.getClubTaskInfoList(clubId, pageNo, pageSize));
    }

    /**
     * 任务完成情况
     */
    @RequestMapping(value = "/taskFinishDetail")
    public APIResponse taskFinishDetail(@RequestBody Map map){

        Long weekDate = MapUtils.getLong(map, "weekDate");
        Integer clubId = MapUtils.getInteger(map, "clubId");
        if (weekDate == null || clubId == null){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        return APIResponse.returnSuccess(
                clubTaskEggService.getTaskActivityInfoOfThisWeek(clubId, new Date(weekDate)));
    }

    @RequestMapping(value = "/photoList")
    public APIResponse<List<TbClubMultimedia>> photoList(@RequestBody Map map){
        return APIResponse.returnSuccess(
                clubHomePageService.photoList(MapUtils.getIntValue(map, "clubId")));
    }

    @RequestMapping(value = "/disable")
    public APIResponse disableClub(@RequestBody Map map, HttpServletRequest request){
        Integer uid = getUid(request, true);
        clubHomePageService.disableClub(uid, MapUtils.getInteger(map, "clubId"));
        return APIResponse.returnSuccess();
    }
}
